<template>
  <div class="big-box">
    <div style="height: 100%;min-height: 400px;min-width: 1200px">
      <div ref="map-container" style="width: 100%;height: calc(100vh - 84px)">
      </div>
    </div>
    <div class="box-util">
      <el-table
        :data="carList"
        max-height="400px"
        @row-click="handleCheckChange">
        <el-table-column
          prop="device_name"
          label="设备名称">
        </el-table-column>
        <el-table-column
          prop="carnum"
          label="绑定车牌号">
        </el-table-column>
        <el-table-column
          prop="name"
          width="50"
          label="状态">
          <template v-slot:default="scope">
            {{ scope.row.online_status == 1 ? '在线' : '离线' }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>

// 以下代码为基于DOMOverlay实现聚合点气泡
import {deptTreeSelect} from "@/api/system/user";
import {listCar} from "@/api/merchant/car";
import {microApi} from "@/api/microPatrolApi";
import {formatDate} from "@/utils";

function ClusterBubble(options) {
  TMap.DOMOverlay.call(this, options);
}

ClusterBubble.prototype = new TMap.DOMOverlay();

ClusterBubble.prototype.onInit = function (options) {
  this.content = options.content;
  this.position = options.position;
};

// 销毁时需要删除监听器
ClusterBubble.prototype.onDestroy = function () {
  this.dom.removeEventListener('click', this.onClick);
  this.removeAllListeners();
};

ClusterBubble.prototype.onClick = function () {
  this.emit('click');
};

// 创建气泡DOM元素
ClusterBubble.prototype.createDOM = function () {
  var dom = document.createElement('div');
  dom.classList.add('clusterBubble');
  dom.innerText = this.content;
  dom.style.cssText = [
    'width: ' + (40 + parseInt(this.content) * 2) + 'px;',
    'height: ' + (40 + parseInt(this.content) * 2) + 'px;',
    'line-height: ' + (40 + parseInt(this.content) * 2) + 'px;',
  ].join(' ');

  // 监听点击事件，实现zoomOnClick
  this.onClick = this.onClick.bind(this);
  // pc端注册click事件，移动端注册touchend事件
  dom.addEventListener('click', this.onClick);
  return dom;
};

ClusterBubble.prototype.updateDOM = function () {
  if (!this.map) {
    return;
  }
  // 经纬度坐标转容器像素坐标
  let pixel = this.map.projectToContainer(this.position);

  // 使文本框中心点对齐经纬度坐标点
  let left = pixel.getX() - this.dom.clientWidth / 2 + 'px';
  let top = pixel.getY() - this.dom.clientHeight / 2 + 'px';
  this.dom.style.transform = `translate(${left}, ${top})`;

  this.emit('dom_updated');
};
window.ClusterBubble = ClusterBubble;

export default {
  name: 'mapping',
  computed: {
    x_token() {
      return this.$store.getters.getWXToken
    },
    member_id() {
      return this.$store.getters.getMemberId
    },
    x_url(){
      return this.$store.getters.getWXUrl
    }
  },
  data() {
    return {
      showDetail: false,
      map: {
        center: {
          lng: 0,
          lat: 0
        },
        zoom: 13
      },
      gpsList: [],
      data: [{
        label: '一级 1',
        children: [{
          label: '二级 1-1',
        }]
      },],
      carIcon: require('../../../assets/car_image/car.png'),
      carList: [],
      deptName: '',
      defaultChoseCar: undefined,
      total: 0,
      pageNum: 1,
      pageSize: 10,
    }
  }, methods: {
    handleCheckChange(row, column, event) {
      console.log(row)
      this.moveVisualAngle(row.gao_lat, row.gao_lng)
    },
    // 视角变幻
    moveVisualAngle(lat, lng,duration=1000) {
      let center = new TMap.LatLng(lat, lng)
      this.map.easeTo({zoom: 16, rotation: 0, center: center}, {duration: duration});
    },
    initMap() {
      this.center = new TMap.LatLng(39.910923647957596, 116.41338729034514);
      this.map = new TMap.Map(this.$refs["map-container"], {
        center: this.center, //设置地图中心点坐标
        zoom: 4, //设置地图缩放级别
      });
      this.map.zoom = 14
    },
    initMark(list) {
      let carMark = []
      let carLabel = []
      // 遍历坐标
      for (let i = 0; i < list.length; i++) {
        if (list[i].gao_lat !== undefined && list[i].gao_lng !== undefined) {

          carMark.push({
            "id": i,   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
            "position": new TMap.LatLng(list[i].gao_lat, list[i].gao_lng),  //点标记坐标位置
            "properties": list[i]
          })
          carLabel.push({
            "id": i,   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
            "styleId": 'label',  //指定样式id
            "position": new TMap.LatLng(list[i].gao_lat, list[i].gao_lng),  //点标记坐标位置
            'content': `${list[i].device_name}`
          })
        }
      }
      new TMap.MultiLabel({
        map: this.map,
        styles: {
          label: new TMap.LabelStyle({
            'color': '#000', //颜色属性
            'size': 15, //文字大小属性
            'offset': {x: 0, y: -30}, //文字偏移属性单位为像素
            'angle': 0, //文字旋转属性
            'alignment': 'top', //文字水平对齐属性
            'verticalAlignment': 'middle' //文字垂直对齐属性
          }),
        },
        geometries: carLabel
      })
      var marker = new TMap.MultiMarker({
        id: 'marker-layer',
        map: this.map,
        styles: {

          default: new TMap.MarkerStyle({
            'width': 34,
            'height': 34,
            'anchor': {
              x: 17,
              y: 21,
            },
            'src': require('../../../assets/car_image/car_online.png'),
          })
        },
        geometries: carMark
      })
      var infoWindow = new TMap.InfoWindow({
        map: this.map,
        enableCustom: true,
        position: new TMap.LatLng(39.984104, 116.307503),
        offset: {x: 0, y: -32} //设置信息窗相对position偏移像素，为了使其显示在Marker的上方
      });
      infoWindow.close()
      marker.on("click", (evt) => {
        debugger
        console.log(evt)
        let date = formatDate(evt.geometry.properties.last_link_time, '{y}-{m}-{d}')
        console.log('info', evt.geometry.properties)
        //设置infoWindow
        infoWindow.open(); //打开信息窗
        infoWindow.setPosition(evt.geometry.position);//设置信息窗位置
        infoWindow.setContent(`<div class="windows-info">
          <div>
          <span class="label">imei号:</span>${evt.geometry.properties.device_imei}
          </div>
          <div><span class="label">设备名称:</span>${evt.geometry.properties.device_name}</div>
          <div>
          <span class="label">GPS绑定车辆:</span>${evt.geometry.properties.car_number ? evt.geometry.properties.car_number : '无'}
          </div>
          <div><span class="label">上次在线时间:</span>${date}</div>
          <div><span class="label">状态:</span>${evt.geometry.properties.status == 1 ? "在线" : "离线"}</div>
          <div><span class="label">绑定车辆:</span>${evt.geometry.properties.name ? evt.geometry.properties.name : '无'}</div>
          <div><span class="label">绑定车牌:</span>${evt.geometry.properties.carnum ? evt.geometry.properties.carnum : '无'}</div>
          </div>
        `);//设置信息窗内容
      })
    },
    showDetailData() {
      console.log('触发点击')
      this.showDetail = true
    },
    tree(data, id, info) {
      for (let i = 0; i < data.length; i++) {
        let item = data[i];

        if (item.id === id) {
          if (item.children) {
            //在对应的组织架构模块下写入车辆信息
            item.children.push(info)
          } else {
            //在对应的组织架构模块下写入车辆信息
            item.children = [info]
          }
          return item;
        } else {
          // item.children 不等于 undefined && item.children.length 大于 0 时
          if (item.children && item.children.length > 0) {
            let res = this.tree(item.children, id, info);
            // 当 res = undefined 时不会进入判断中
            // 也就是不会return
            if (res) return res;
          }
        }
      }
    },
    init() {
      deptTreeSelect().then(response => {
        this.data = response.data;
      });
      microApi(this.x_url,{
        "busiCode": "deviceListWithMonitor",
        "x_token": this.x_token,
        "body": {"member_id": this.member_id, "global_status": -99, "pageSize": 500, "pageNo": 1}
      }).then(res => {
        this.carList = res.data
        listCar({
          pageNum: 1,
          pageSize: 500
        }).then(response => {
          if (response.code == 200) {
            let carInfo = response.rows
            for (let j = this.carList.length - 1; j >= 0; j--) {
              for (let i = carInfo.length - 1; i >= 0; i--) {
                if (carInfo[i].imei == null || carInfo[i].imei == '') {
                  console.log('remove')
                  carInfo.splice(i, 1)
                  continue
                }
                if (carInfo[i].imei == this.carList[j].device_imei) {
                  console.log(this.carList[j])
                  console.log(carInfo[i])
                  this.$set(this.carList[j], 'name', carInfo[i].name)
                  this.$set(this.carList[j], 'carnum', carInfo[i].carnum)
                  if (this.defaultChoseCar==carInfo[i].id){
                    console.log(this.carList[j].gao_lat,this.carList[j].gao_lng)
                    this.moveVisualAngle(this.carList[j].gao_lat,this.carList[j].gao_lng)
                  }
                }
              }
            }
            this.initMark(this.carList)
          }
        })
      })
    },
  },
  mounted() {
    if (this.$route.query && this.$route.query.defaultChoseCar) {
      this.defaultChoseCar = this.$route.query.defaultChoseCar
    }
    // 初始化地图
    this.initMap()
    if (this.x_token == null) {
      this.$store.dispatch('LoginWX').then(() => {
        this.init()
      })
    } else {
      this.init()
    }
    },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
}

</script>
<style lang="scss">
.clusterBubble {
  border-radius: 50%;
  color: #fff;
  font-weight: 500;
  text-align: center;
  opacity: 0.88;
  background-image: linear-gradient(139deg, #4294FF 0%, #295BFF 100%);
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.20);
  position: absolute;
  top: 0px;
  left: 0px;
}

.big-box {
  z-index: 1;
  width: 100%;
  height: 100%;
  //min-height: 800px;
  //min-width: 600px;
  position: relative;
}

.box-util {
  float: left;
  z-index: 1001;
  position: absolute;
  overflow-y: scroll;
  left: 1%;
  top: 1%;
  width: 20%;
  min-width: 300px;
  background: rgba(255, 255, 255, 0.8);
}

.sample.active {
  background: rgba(0, 0, 0, 0.75);
  color: #fff;
}

.box-detail {
  z-index: 100;
  position: absolute;
  left: 1%;
  right: 1%;
  bottom: 1%;
  min-height: 200px;
}

.windows-info {
  text-align: left;

  .label {
    font-weight: bold;
  }
}
</style>
